<script setup>
  import * as echarts from 'echarts';
  import { onMounted, reactive, ref, onBeforeUnmount, nextTick, inject, watch } from 'vue';
  import { eventBus } from '@/function/bus/index.js';
  // import geoJSON from '@/assets/json/China_Province/330000.json';

  defineOptions({name: 'echarts'});
  let geoJSON = null;
  const mapParams = inject('mapParams');
  // 深度监听
  watch(() => [mapParams], () => {
    loadGoJson();
  }, {deep: true})
  onMounted(() => {
    loadGoJson();
  });
  async function loadGoJson() {
    loading.value = true;
    geoJSON = mapParams.geoJSON;
    loadEchartsMap()
  }

  const loading = ref(false);

  // 地图实例
  const myChart = ref(null);
  // 地图配置
  const option = reactive({
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return params.name + '：' + (params.value || 0);
      },
    },
    series: [
      // 地图配置
      {
        type: "map",
        geoIndex: 0,
        data: [],
      },
    ],
    geo: [{
      map: "map_area",
      layoutCenter: ['50%', '50%'],
      layoutSize: '92%',
      z: 2,
      label: {
        show: true,
        fontSize: 13,
        color: '#1bfeff',
      },
    }]
  })
  // 加载Echarts地图
  const loadEchartsMap = () => {
    disposeEchartsMap();
    setTimeout(() => {
      // 初始化
      myChart.value = echarts.init(document.getElementById('mainMap'));
      // 监听窗口大小变化
      window.addEventListener("resize", () => {
        if (myChart.value) myChart.value.resize();
      })
      // 点击事件
      myChart.value.on('click', (mapParams) => {
        eventBus.emit('areaChange', mapParams);
      });
      // 鼠标移入事件
      myChart.value.on('mouseover', (mapParams) => {
        // console.log('mouseover', mapParams);
      });
      // 鼠标移出事件
      myChart.value.on('mouseout', (mapParams) => {
        // console.log('mouseout', mapParams);
      });
      option.series[0].data = (geoJSON?.features || []).map((item) => {
        return {
          name: item.properties.name,
          value: item.properties.value,
          code: item.properties.adcode,
          parent: item.properties.parent,
        }
      })
      // 加载地图
      echarts.registerMap("map_area", geoJSON);
      myChart.value.setOption(option);
      loading.value = false;
    }, 500)
  }
  // 销毁地图
  const disposeEchartsMap = () => {
    window.removeEventListener("resize", () => {
      if (myChart.value) myChart.value.resize();
    })
    if (myChart.value) myChart.value.dispose();
  }

  // 销毁
  onBeforeUnmount(() => {
    disposeEchartsMap();
  })

  // 子组件暴露
  defineExpose({});

</script>

<template>
  <div id="mainMap" style="width: 100%;height: 100%;" v-loading="loading"></div>
</template>

<style lang="less" scoped>

</style>
